<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
//require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

const animationDuration = 1000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData:{
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ category, barData } = {}){
      this.chart.setOption({
        tooltip: {
          trigger: "axis"
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 10,
          top:30,
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: category,
          axisTick: {
            show: false,
            alignWithLabel: true
          },
          axisLine: {
            lineStyle: {
              color: "#999999",
            },
          },
          axisLabel:{
            interval:barData.length>8?'auto':0,
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: "#efefef",
            },
          },
          axisLine: {
            show:true,
            lineStyle: {
              color: "#999999",
            },
          },
        }],
        series: [{
          name: '',
          type: 'bar',
          barWidth: '20%',
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#1890ff" },
                { offset: 1, color: "#37c5d3" },
              ]),
            },
          },
          data: barData,
          animationDuration
        }]
      })
    }
  }
}
</script>
